import React, { useState } from 'react'
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Space
} from 'antd'
import type { ColumnsType } from 'antd/es/table'

// 定义用户数据类型
interface User {
  id: number
  name: string
  email: string
  age: number
}

const App: React.FC = () => {
  const [users, setUsers] = useState<User[]>([
    { id: 1, name: '张三', email: 'zhangsan@example.com', age: 25 },
    { id: 2, name: '李四', email: 'lisi@example.com', age: 30 },
    { id: 3, name: '王五', email: 'wangwu@example.com', age: 35 },
  ])
  
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [form] = Form.useForm<Partial<User>>()
  const [searchKeyword, setSearchKeyword] = useState('')

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="middle">
          <Button type="primary" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button danger size="small" onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  // 打开添加用户模态框
  const showAddModal = () => {
    setEditingUser(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  // 打开编辑用户模态框
  const handleEdit = (user: User) => {
    setEditingUser(user)
    form.setFieldsValue(user)
    setIsModalVisible(true)
  }

  // 删除用户
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setUsers(users.filter(user => user.id !== id))
        message.success('用户删除成功')
      },
    })
  }

  // 提交表单（添加或更新用户）
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        if (editingUser) {
          // 更新用户
          setUsers(users.map(user => 
            user.id === editingUser.id ? { ...user, ...values } : user
          ))
          message.success('用户更新成功')
        } else {
          // 添加新用户
          const newUser: User = {
            id: users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1,
            ...values as Omit<User, 'id'>
          }
          setUsers([...users, newUser])
          message.success('用户添加成功')
        }
        setIsModalVisible(false)
        form.resetFields()
      })
      .catch(info => {
        console.log('表单验证失败:', info)
      })
  }

  // 根据搜索关键词过滤用户
  const filteredUsers = users.filter(user => 
    user.name.toLowerCase().includes(searchKeyword.toLowerCase())
  )

  // 处理搜索输入变化
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKeyword(e.target.value)
  }

  // 处理搜索提交
  const handleSearch = () => {
    // 搜索逻辑已在filteredUsers中实现
  }

  return (
    <div className="App" style={{ padding: 20, maxWidth: 900, margin: '0 auto' }}>
      <h1 style={{ textAlign: 'center', marginBottom: 20 }}>用户管理系统</h1>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Button type="primary" onClick={showAddModal}>
          添加用户
        </Button>
        <Input
          placeholder="搜索用户姓名"
          value={searchKeyword}
          onChange={handleSearchChange}
          onPressEnter={handleSearch}
          style={{ width: 200 }}
        />
      </div>
      <Table columns={columns} dataSource={filteredUsers} rowKey="id" />

      <Modal
        title={editingUser ? '编辑用户' : '添加用户'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={() => setIsModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
          initialValues={{ remember: true }}
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[
              { required: true, message: '请输入年龄' },
              { 
                validator: (_, value) => {
                  if (!value || isNaN(value)) {
                    return Promise.reject(new Error('请输入有效的数字'));
                  }
                  const numValue = Number(value);
                  if (numValue < 18 || numValue > 100) {
                    return Promise.reject(new Error('年龄必须在18-100之间'));
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input type="number" placeholder="请输入年龄" min={18} max={100} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default App